var timeout = 3000
var admin_token_key = "xin-token"

var xin_request = function () {
    var ajax = function (url, method, args, contentType, headers, successFunc, errorFunc) {
        var admin_token_value = $.cookie(admin_token_key)
        if (headers == undefined) {
            headers = {}
        }

        headers[admin_token_key] = admin_token_value

        $.ajax({
            url: base_url + url,
            type: method,
            data: args,
            cache: false,
            timeout: timeout,
            contentType: contentType,
            dataType: 'json',
            headers: headers,
            success: function (data, textStatus, jqXHR) {
                if (data.code == err_unauthorized) {
                    $.cookie(admin_token_key, '')
                    window.location.href = 'login.html'
                }
                if (data.code == err_not_found) {
                    window.location.href = '404.html'
                }
                successFunc(data, textStatus, jqXHR)
            },
            error: errorFunc,
        })
    }

    var defaultSuccessFunc = function (data, status, jqXHR) {

    }

    var defaultErrFunc = function (jqXHR, textStatus, errorTh) {
        console.log('请求接口出错', textStatus, errorTh)
        throw errorTh
    }


    return {
        exec: function (url, method, args, contentType, headers, successFunc, errorFunc) {
            if (contentType == undefined || contentType == '') {
                contentType = 'application/json; charset=utf-8'
            }

            if (errorFunc == undefined || errorFunc == '') {
                errorFunc = defaultErrFunc
            }

            if (method == 'POST' || method == 'post' || method == 'PUT' || method == 'put') {
                if (args != undefined && args != '') {
                    args = JSON.stringify(args)
                }
            }

            ajax(url, method, args, contentType, headers, successFunc, errorFunc)
        },

        get: function (url, args, successFunc, errorFunc) {
            ajax(url, "GET", args, 'application/json; charset=utf-8', {}, successFunc, errorFunc)
        },

        del: function (url, args, successFunc, errorFunc) {
            ajax(url, "DELETE", args, 'application/json; charset=utf-8', {}, successFunc, errorFunc)
        },

        post: function (url, args, successFunc, errorFunc) {
            if (args != undefined && args != '') {
                args = JSON.stringify(args)
            }
            ajax(url, "POST", args, 'application/json; charset=utf-8', {}, successFunc, errorFunc)
        },
        put: function (url, args, successFunc, errorFunc) {
            if (args != undefined && args != '') {
                args = JSON.stringify(args)
            }
            ajax(url, "PUT", args, 'application/json; charset=utf-8', {}, successFunc, errorFunc)
        },

    }

}();